package ua.kharkov.khpi.tarasenko.bach.web.command.admin;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.kharkov.khpi.tarasenko.bach.core.Constant;
import ua.kharkov.khpi.tarasenko.bach.core.LocalizedResourceManager;
import ua.kharkov.khpi.tarasenko.bach.core.EShopException;
import ua.kharkov.khpi.tarasenko.bach.core.db.ConnectionManager;
import ua.kharkov.khpi.tarasenko.bach.core.db.DBUtils;
import ua.kharkov.khpi.tarasenko.bach.dao.core.DAOFactory;
import ua.kharkov.khpi.tarasenko.bach.dao.core.item.ItemDAO;
import ua.kharkov.khpi.tarasenko.bach.web.command.Command;

/**
 * Command to remove item.
 * 
 * @author oleksandr
 * 
 */
public class RemoveItemCommand extends Command {
	private static final Logger log = Logger.getLogger(RemoveItemCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws EShopException {

		String forward = Constant.COMMAND_SHOW_ITEMS_LIST;
		String errorMessage = null;
		Connection conn = null;

		String itemIdString = request.getParameter(Constant.ATTRIBUTE_ITEM_ID);
		if (log.isTraceEnabled()) {
			log.trace("Got parameter from request "
					+ Constant.ATTRIBUTE_ITEM_ID + "=" + itemIdString);
		}

		// Create LocalizedResourceManager to get localized error messages
		LocalizedResourceManager LRManager = getLocalizedResourceManager(request);

		if ((itemIdString == null) || (itemIdString.isEmpty())) {

			errorMessage = LRManager
					.getMessage("error_message.item_id_not_spec");
		} else {

			int itemId = Integer.valueOf(itemIdString);
			try {
				conn = ConnectionManager.getConnection();
				ItemDAO itemDAO = DAOFactory.getDAOFactory(
						DAOFactory.DAO_TYPE.MYSQL).getItemDAO(conn);
				int rowsDeleted = itemDAO.deleteItem(itemId);

				// Item wasn't updated
				if (rowsDeleted != 1) {
					errorMessage = LRManager
							.getMessage("error_message.item_id_not_found")
							+ itemId;
				} else {

					// Everything is ok, commit
					DBUtils.commitAndClose(conn);
				}
			} catch (EShopException e) {
				DBUtils.rollBackAndClose(conn);
				throw e;
			} finally {
				if (conn != null) {
					DBUtils.close(conn);
				}
			}
		}

		if (errorMessage != null) {
			forward = processError(request, errorMessage);
		}

		if (log.isDebugEnabled()) {
			log.debug("Forward to " + forward);
		}
		return forward;
	}
}
